package com.dingpeikeji.quickdeer.modules.rentproduct.service;

import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.modules.orders.dao.TOrdersDao;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.payinfo.dao.TPayinfoDao;
import com.dingpeikeji.quickdeer.core.modules.payinfo.entity.TPayinfo;
import com.dingpeikeji.quickdeer.modules.rentproduct.dao.RentproductSettleDao;
import com.dingpeikeji.quickdeer.modules.rentproduct.dao.TOfficeCreditDao;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TOfficeCredit;

@Service
@Transactional(readOnly = true)
public class RentproductSettleService {
	@Autowired
	private RentproductSettleDao rentproductSettleDao;
	@Autowired
	private TOfficeCreditDao officeCreditDao;
	@Autowired
	private TPayinfoDao payinfoDao;
	@Autowired
	private TOrdersDao orderDao;

	/**
	 * 查询线下支付和信用支付的订单列表
	 * @return
	 */
	public Page<TPayinfo> findPage(Page<TPayinfo> page, TPayinfo payinfo){
		payinfo.setPage(page);
		page.setList(rentproductSettleDao.findList(payinfo));
		return page;
	}
	
	/**
	 * 人工结算
	 * @return
	 */
	public void settle(TPayinfo payinfo) throws Exception{
		if(rentproductSettleDao.payinfoSettleStatusYes(payinfo)==0){
			throw new RuntimeException();
		}
		if(payinfo.getDiscounttype().equals(TOrders.PAY_WAY_CREDIT)){ // 信用支付
			payinfo = payinfoDao.get(payinfo.getDiscountid().toString());
			TOrders orders = orderDao.get(payinfo.getOrders().getId());
			TOfficeCredit officeCredit = new TOfficeCredit();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(payinfo.getCreateDate());
			officeCredit.setOffice(orders.getOffice());
			officeCredit.setCredityears(calendar.get(Calendar.YEAR));
			officeCredit.setCreditmonths(calendar.get(Calendar.MONTH));
			officeCredit.setChecked(payinfo.getPayfee());
			List<TOfficeCredit> officeCreditList = officeCreditDao.findList(officeCredit);
			if(officeCreditList!=null&&!officeCreditList.isEmpty()){ // 存在信用记录则更新金额
				if(officeCreditDao.updateChecked(officeCredit)==0){
					throw new RuntimeException();
				}
			} else { // 不存在信用记录则新建
				// TODO 月使用额度表的月使用额度字段不知道该填什么
//				officeCredit.setTotalcredit(totalcredit);
//				if(officeCreditDao.insert(officeCredit)==0){
//					throw new RuntimeException();
//				}
			}
		}
	}
}
